import React, { useEffect, useRef, useState } from 'react';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import ProForm, { ModalForm, ProFormText, ProFormSelect, ProFormRadio, ProFormDatePicker, ProFormDigit } from '@ant-design/pro-form';
import { Button, FormInstance, Modal } from 'antd';
import { history } from 'umi';
import { getPatientHospitalizationInfo, getWorkerServiceList, getPatientList } from '@/services/order/api';
import { getDateValue, isNull, MsgType, showMsg } from '@/utils/utils';
import { OptType } from '@/utils/constants';
import moment from 'moment';

const OptForm: React.FC<any> = (props) => {
  const { 
    handleModalVisible, 
    handleAdd, 
    actionRef,
    record = {},
    onRefresh,
    optType
  } = props;
  const { confirm } = Modal;

  const [patientInfo, setPatientInfo] = useState<ORDERAPI.PatientHospitalInfo>({});
  const formRef = useRef<FormInstance>();
  const [serviceType, setServiceType] = useState<string>('I');
  const [showDialog, setShowDialog] = useState(false);

  const checkExits = async(no: string, params) => {
    await getWorkerServiceList({ current: 1, pageSize: 9999, no }).then(res => {
      const result = (res.record_list || []).find(item => item.order_status === 'C' || item.order_status === 'P');
      if (!isNull(result)) {
        // setShowDialog(true);
        console.log('result', result);
        confirm({
          title: `系统检查该患者存在未完成的${result.service_type === 'I' ? '院内' : '院外'}服务档案，是否继续创建？`,
          icon: <ExclamationCircleOutlined />,
          okText: '跳转到已存在档案',
          cancelText: '继续',
          onOk() {
            history.push({
              pathname: `/order/worker/patient/archiveInfo`,
              query: {
                order_id: result.order_id as string,
              },
            });
          },
          onCancel() {
            console.log('Cancel');
            if (!isNull(params)) {
              fetchPatientInfo(params, 'true')
            }
          },
        });
      }
    }).catch(error => {
      showMsg(error?.data?.errmsg);
    });
  }

  // 患者信息
  const fetchPatientInfo = async (params, isCard) => {
    try {
      const data: ORDERAPI.PatientHospitalInfo[] = await getPatientHospitalizationInfo(params);
      let info: ORDERAPI.PatientHospitalInfo = {};

      if (Array.isArray(data) && data.length > 0) {
        info = data[0];
        setPatientInfo(info);
        formRef.current?.setFieldsValue({
          patient_name: info?.patient_name,
          address: `${info.ward_address}${info.bed_no}床位`
        });
        if (!isCard) {
          checkExits(info.visit_no);
        }
        fetchlxl(info.patient_id, info.ic_card_no);
      } else {
        showMsg('未找到患者信息', MsgType.INFO);
        formRef.current?.setFieldsValue({
          patient_name: null,
          address: null
        });
      }
    } catch (error) {
      console.log(error);
      showMsg(error?.data?.errmsg);
    }
  }

  // 获得患者联系人信息
  const fetchlxl = (id, cardno) => {
    getPatientList({ patient_id: id, ic_card_no: cardno }).then(res => {
      formRef.current?.setFieldsValue({
        liaison_name: res ? res[0].patient_name : undefined,
        liaison_mobile: res ? res[0].mobile : undefined
      });
    })
  }
  useEffect(() => {
    if (record.order_id) {
      setServiceType(record.service_type)
    }
  }, [record]);

  return <ModalForm
      title="新建/编辑档案"
      width="90%"
      visible
      modalProps={{
        maskClosable: false
      }}
      className="worker-modal"
      layout="horizontal"
      formRef={formRef}
      onVisibleChange={handleModalVisible}
      onFinish={async (value) => {
        console.log(formRef.current?.getFieldsValue());

        // if (value.begin_date && value.end_date) {
        //   if (getDateValue(value.begin_date) > getDateValue(value.end_date)) {
        //     formRef.current?.setFieldsValue({
        //       end_date: null
        //     })
        //     showMsg('结束时间不能早于开始时间', MsgType.INFO);
        //     return;
        //   }
        // }
        const values = formRef.current?.getFieldsValue();
        values.begin_date = moment(values.begin_date).format('YYYYMMDD')
        // values.end_date = moment(values.end_date).format('YYYYMMDD')
        if (serviceType === 'I') {
          value = Object.assign({}, values, { patient_id: record.patient_id || patientInfo.patient_id, identity_no: record.identity_no || patientInfo.identity_no });
        } else {
          value = Object.assign({}, values);
        }
        console.log(value);
        if (serviceType === 'I') {
          if (value.admission_num.length < 6 || value.admission_num.length > 14) {
            showMsg('请输入正确的住院号', MsgType.INFO);
            return;
          }
        } else {
          console.log(123)
          if (value.identity_no.length !== 18) {
            showMsg('请输入18位数的身份证号码', MsgType.INFO);
            return;
          }
        }
        value.admission_num = patientInfo.visit_no;
        const success = await handleAdd(value as any);
        if (success) {
          handleModalVisible(false);
          onRefresh && onRefresh();
          actionRef.current?.reload();
        }
      }}
      submitter={{
        render: (props, doms) => {
          return [
            <Button 
            key="cancle" 
            onClick={() => {
              handleModalVisible(false)
            }}
            >
            取消
          </Button>,

          <Button 
            key="save" 
            type="primary"
            onClick={async () => {
              props.form?.submit();
            }}
            >
            保存
          </Button>,
            optType !== OptType.EDIT && <Button 
              key="dispatch"
              type="primary"
              onClick={async () => {
                try {
                  await props.form?.validateFields();
                  let values;
                  if (serviceType === 'I') {
                    values = Object.assign({},  props.form?.getFieldsValue(), { patient_id: record.patient_id || patientInfo.patient_id, identity_no: record.identity_no || patientInfo.identity_no });
                  } else {
                    values = Object.assign({},  props.form?.getFieldsValue());
                  }
                  
                  if (serviceType === 'I') {
                    if (values.admission_num.length < 6 || values.admission_num.length > 14) {
                      showMsg('请输入正确的住院号', MsgType.INFO);
                      return;
                    }
                  } else {
                    if (values.identity_no.length !== 15 && values.identity_no.length !== 18) {
                      showMsg('请输入15或18位数的身份证号码', MsgType.INFO);
                      return;
                    }
                  }
                  values.begin_date = moment(values.begin_date).format('YYYYMMDD')
                  values.end_date = moment(values.end_date).format('YYYYMMDD')
                  const data = await handleAdd(values as any);
                  if (data) {
                    history.push({
                      pathname: '/order/worker/patient/archiveInfo',
                      query: {
                        order_id: data.order_id
                      }
                    })
                  }
                } catch (error) {
                  console.log(error);
                }
              }}
            >派单</Button>
          ]
        }
      }}>
      <ProForm.Group>
        <ProFormRadio.Group
          name="service_type"
          label="服务方式"
          width="md"
          disabled={optType === OptType.EDIT}
          initialValue={record.service_type || 'I'}
          fieldProps={{
            onChange: (e: any) => {
              setServiceType(e.target.value);
              formRef.current?.setFieldsValue({
                admission_num: null,
                patient_name: null,
                address: null
              })
            }
          }}
          options={[
            {
              label: '院内',
              value: 'I'
            },
            {
              label: '院外',
              value: 'O'
            }
          ]}
        />
        <ProFormRadio.Group
          name="service_content"
          label="服务内容"
          width="md"
          initialValue={record.service_content || 'H'}
          options={[
            {
              label: '护理',
              value: 'H'
            },
            {
              label: '陪诊',
              value: 'P'
            },
          ]}
        />
      </ProForm.Group>

      <ProForm.Group>
        <ProFormText
          rules={
            [
              {
                required: true
              }
            ]
          }
          label={serviceType === 'I' ? '病案号' : '身份证号'}
          width="md"
          name={serviceType === 'I' ? 'admission_num' : 'identity_no'}
          initialValue={serviceType === 'I' ? record.admission_num : record.identity_no}
          readonly={optType === OptType.EDIT}
          fieldProps={{
            readOnly: optType === OptType.EDIT,
            onBlur: (e: any) => {
              const value = e.target.value;

              if (serviceType !== 'I') {
                if (value && value.trim().length !== 18) {
                  showMsg('请输入18位的身份证号码', MsgType.INFO);
                  return;
                }
                if (value && value.trim().length === 18) {
                  checkExits(value);
                }
                return;
              }
              if (value && value.trim().length) {
                if (value.includes('R')) {
                  fetchPatientInfo({ out_visit_no: value });
                } else if (value.length === 15 || value.length === 18) {
                  // fetchPatientInfo({ id_no: value }, true);
                  checkExits(value, { id_no: value })
                } else {
                  fetchPatientInfo({ out_case_no: value });
                }
              } 
            }
          }}
        />
        <ProFormText
          rules={
            [
              {
                required: true
              }
            ]
          }
          label="患者姓名"
          width="md"
          readonly={serviceType === 'I'}
          name="patient_name"
          initialValue={record.patient_name}
        />
        
      </ProForm.Group>
      
      <ProForm.Group>
        <ProFormText
          rules={
            [
              {
                required: true
              }
            ]
          }
          label="服务地址"
          width="md"
          name="address"
          readonly={serviceType === 'I'}
          initialValue={record.address}
        />
      </ProForm.Group>

      <ProForm.Group>
        <ProFormDatePicker
          rules={
            [
              {
                required: true
              }
            ]
          }
          label="开始时间（估）"
          width="md"
          name="begin_date"
          initialValue={record.begin_date}
          fieldProps={{
            onChange: (val) => {
              const begin = formRef.current?.getFieldValue('begin_date');
              const end = formRef.current?.getFieldValue('end_date');

              if (end && getDateValue(begin) > getDateValue(end)) {
                formRef.current?.setFieldsValue({
                  end_date: null
                })
                showMsg('结束时间不能早于开始时间', MsgType.INFO);
                return;
              }
              if (end) {
                const day = moment(end).diff(begin, 'day') + 1;
                formRef.current?.setFieldsValue({ nurse_day: day });
              }
            }
          }}
        />
        {/* <ProFormDatePicker
          rules={
            [
              {
                required: true
              }
            ]
          }
          label="结束时间（估）"
          width="md"
          name="end_date"
          initialValue={record.end_date}
          fieldProps={{
            onChange: (val) => {
              const begin = formRef.current?.getFieldValue('begin_date');
              const end = formRef.current?.getFieldValue('end_date');
              if (begin && getDateValue(begin) > getDateValue(end)) {
                formRef.current?.setFieldsValue({
                  end_date: null
                })
                showMsg('结束时间不能早于开始时间', MsgType.INFO);
                return;
              }
              if (begin) {
                const day = moment(end).diff(begin, 'day') + 1;
                formRef.current?.setFieldsValue({ nurse_day: day });
              }
            }
          }}
        />
        <ProFormText
          label="护理天数"
          width="md"
          name="nurse_day"
          initialValue={record.nurse_day}
          readonly
          fieldProps={{
            suffix: '天'
          }}
        /> */}
      </ProForm.Group>
      <ProForm.Group>
        <ProFormSelect 
          label="服务星级"
          width="md"
          rules={
            [
              {
                required: true
              }
            ]
          }
          name="rank"
          options={
            [
              {
                label: '三星级',
                value: '3'
              },
              {
                label: '四星级',
                value: '4'
              },
              {
                label: '五星级',
                value: '5'
              }
            ]
          }
          initialValue={record.rank}
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormText
          label="联系人"
          width="md"
          name="liaison_name"
          initialValue={record.liaison_name}
        />
        <ProFormText
          label="联系电话"
          width="md"
          name="liaison_mobile"
          initialValue={record.liaison_mobile}
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormText
          label="备注"
          width="md"
          name="remark"
          initialValue={record.remark}
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormText
          label="下单渠道"
          width="md"
          name="channel"
          readonly
          // options={[
          //   {
          //     label: '小程序',
          //     value: 'M'
          //   },
          //   {
          //     label: '院内',
          //     value: 'H'
          //   }
          // ]}
          initialValue="院内"
        />
      </ProForm.Group>
    </ModalForm>
}
export default OptForm;
